<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    top="100px"
    :close-on-click-modal="false"
    class="page-supplier-prod-select supplierProdSelect"
  >
    <div class="mod-order-order">
      <div class="screening-conditions">
        <el-form
          :inline="true"
          :model="dataForm"
          @submit.prevent
          @keyup.enter="getDataList(page)"
        >
          <div class="search">
            <el-form-item
              :label="$t('publics.code') + '：'"
              :label-width=" lang === 'en' ? '145px' : '85px'"
            >
              <el-input
                v-model="dataForm.partyCode"
                :placeholder="$t('publics.code')"
                clearable
              />
            </el-form-item>

            <el-form-item>
              <div
                class="default-btn primary-btn"
                @click="searchProd()"
              >
                {{ $t("order.query") }}
              </div>
              <div
                class="default-btn"
                @click="clear()"
              >
                {{ $t("shop.resetMap") }}
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="main">
        <div class="content">
          <!-- 列标题 -->
          <div :class="['tit']">
            <el-row style="width: 100%">
              <el-col :span="1">
                <span class="item">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="indeterminateItem()"
                    :disabled="disable"
                    @change="checkAllProd()"
                  />
                </span>
              </el-col>
              <el-col
                :span="7"
                class="column-title"
              >
                <span class="item">{{ $t("product.prodInfo") }}</span>
              </el-col>
              <el-col
                :span="3"
                class="column-title"
              >
                <span class="item">{{ $t("product.prodStatus") }}</span>
              </el-col>
              <el-col
                :span="6"
                class="column-title"
              >
                <span class="item">{{ $t("product.productSpecifi") }}</span>
              </el-col>
              <el-col
                :span="3"
                class="column-title"
              >
                <span class="item">{{ $t("publics.code") }}</span>
              </el-col>
              <el-col
                :offset="1"
                :span="2"
                class="column-title"
              >
                <span class="item">{{ $t("coupon.stock") }}</span>
              </el-col>
            </el-row>
          </div>

          <div
            v-for="(prod, index) in dataList"
            :key="prod.prodId"
            class="prod"
            style="margin-bottom: 10px"
          >
            <div class="prod-cont">
              <el-row style="width: 100%">
                <el-col
                  :span="1"
                  style="height: 100%"
                >
                  <div class="item">
                    <el-checkbox
                      v-model="prod.check"
                      :disabled="prod.disable"
                      @change="checkProd(index)"
                    />
                  </div>
                </el-col>
                <el-col
                  :span="7"
                  class="public-height"
                >
                  <div class="prod-item">
                    <div
                      class="item"
                      style="margin-left:15%;width:80%"
                    >
                      <div
                        class="prod-image"
                        style="margin-right:0"
                      >
                        <ImgShow
                          :src="prod.pic"
                          :img-style="{width:'60px',height:'60px'}"
                        />
                      </div>
                      <el-tooltip
                        effect="dark"
                        :content="prod.prodName"
                        placement="top"
                      >
                        <div class="prod-name">
                          {{ prod.prodName }}
                        </div>
                      </el-tooltip>
                    </div>
                  </div>
                </el-col>
                <el-col
                  :span="3"
                  style="height: 100%"
                >
                  <div class="item">
                    {{
                      [
                        $t("publics.LowerShelf"),
                        $t("publics.UpperShelf"),
                        $t("publics.violationShelf"),
                        $t("publics.pendingReview"),
                      ][prod.status]
                    }}
                  </div>
                </el-col>
                <el-col
                  :span="13"
                  style="height: 100%"
                >
                  <div
                    v-for="(sku, skuIndex) in prod.skuList"
                    :key="sku.skuId"
                    class="items name"
                    :class="{'public-height': prod.skuList.length === 1}"
                  >
                    <el-row
                      style="width: 100%"
                      class="public-height"
                    >
                      <el-col
                        :span="1"
                        style="height: 100%"
                      >
                        <div class="item">
                          <el-checkbox
                            v-if="prod.skuList.length > 1"
                            v-model="sku.check"
                            :disabled="sku.disable"
                            @change="checkSku(index, skuIndex)"
                          />
                          <span />
                        </div>
                      </el-col>
                      <el-col
                        :span="9"
                        style="height: 100%"
                      >
                        <div class="item">
                          {{ sku.skuName || '-' }}
                        </div>
                      </el-col>
                      <el-col
                        :span="8"
                        style="height: 100%"
                      >
                        <div class="item">
                          {{ sku.partyCode }}
                        </div>
                      </el-col>
                      <el-col
                        :span="6"
                        style="height: 100%"
                      >
                        <div class="item">
                          {{ sku.stocks }}
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          <div
            v-if="!dataList||dataList.length===0"
            class="notData-tip"
          >
            {{ $t("order.noData") }}
          </div>
        </div>
        <el-pagination
          v-if="dataList.length"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div>
    </div>
    <template #footer>
      <!-- 提交及返回按钮 -->
      <div class="submit-box">
        <div
          class="default-btn"
          @click="back()"
        >
          {{
            $t("shopFeature.edit.back")
          }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="submitProds()"
        >
          {{
            $t("groups.submit")
          }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

const emit = defineEmits(['refreshSelectSupplier'])
const props = defineProps({
  type: {
    // 0：普通商品， 1：供应商商品
    default: 0,
    type: Number
  },
  dataUrl: {
    default: '/prod/prod/prodSkuPage',
    type: String
  }
})

const visible = ref(false)
const dataForm = reactive({
  product: ''
})
const lang = localStorage.getItem('bbcLang')
const supplierId = ref(0)
let selectProds = []
let selectSkuIds = []
let disableSkuIds = []
const dataList = ref([])
const prodName = ref('')
const checkAll = ref(false)
const disable = ref(false)
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const dataListSelections = ref([])

let page = {
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
}

onActivated(() => {
  getDataList()
})

// 获取数据列表
const init = (data) => {
  supplierId.value = data.supplierId
  disableSkuIds = data.skuIds ? data.skuIds : []
  visible.value = true
  checkAll.value = false
  selectProds = []
  selectSkuIds = []
  page = {
    total: 0,
    currentPage: 1,
    pageSize: 10
  }
  pageIndex.value = 1
  pageSize.value = 10
  totalPage.value = 0
  getDataList()
}
defineExpose({ init })
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          prodName: prodName.value || '',
          partyCode: dataForm.partyCode ? dataForm.partyCode : '',
          status: 1,
          supplierId: supplierId.value
        }
      )
    )
  }).then(({ data }) => {
    loadCheck(data)
    dataList.value = data.records
    page.total = data.total
    totalPage.value = data.total
  })
}
const loadCheck = (data) => {
  let _checkAll = true
  data.records.forEach(prod => {
    if (props.type === 0) {
      prod.type = 1
    }
    prod.pic = checkFileUrl(prod.pic)
    let check = true
    prod.disable = true
    prod.skuList.forEach(sku => {
      // 禁用已选择的sku及商品
      if (containsId(prod, sku.skuId)) {
        sku.check = true
        sku.disable = true
      } else {
        prod.disable = false
        sku.disable = false
        sku.check = containsId(prod, sku.skuId)
      }
      if (!sku.check) {
        // 普通商品
        sku.check = selectSkuIds.indexOf(sku.skuId) !== -1
      }
      if (check && !sku.check) {
        check = false
      }
    })
    prod.check = check
    if (_checkAll && !prod.check) {
      _checkAll = false
    }
  })
  disable.value = _checkAll
  checkAll.value = _checkAll
}

// eslint-disable-next-line no-unused-vars
const containsId = (prod, skuId) => {
  return disableSkuIds.indexOf(skuId) !== -1
}
const selectProduct = (prod, sku) => {
  // 勾选
  if (sku.check) {
    if (props.type === 0) {
      if (selectSkuIds.indexOf(sku.skuId) !== -1) {
        return
      }
      selectProds.push({
        prodId: prod.prodId,
        skuId: sku.skuId,
        prodName: prod.prodName,
        skuName: sku.skuName,
        stocks: sku.stocks,
        partyCode: sku.partyCode,
        pic: prod.pic
      })
    } else if (props.type === 1) {
      // 普通商品
      if (selectSkuIds.indexOf(sku.skuId) !== -1) {
        return
      }
      selectProds.push({
        prodId: prod.prodId,
        prodName: prod.prodName,
        pic: prod.pic,
        skuId: sku.skuId,
        skuName: sku.skuName,
        stocks: sku.stocks,
        partyCode: sku.partyCode,
        minOrderQuantity: sku.minOrderQuantity,
        purchasePrice: sku.purchasePrice,
        supplierProdId: sku.supplierProdId,
        type: prod.type
      })
    }
    selectSkuIds.push(sku.skuId)
  } else {
    if (selectSkuIds.indexOf(sku.skuId) === -1) {
      return
    }
    // 取消勾选
    for (let i = 0; i < selectProds.length; i++) {
      if (selectProds[i].skuId === sku.skuId) {
        selectProds.splice(i, 1)
      }
    }
    selectSkuIds.splice(selectSkuIds.indexOf(sku.skuId), 1)
  }
}
const checkAllProd = () => {
  dataList.value.forEach(prod => {
    prod.check = checkAll.value
    prod.skuList.forEach(sku => {
      // 勾选或取消勾选没有被禁用的sku
      if (!sku.disable) {
        sku.check = checkAll.value
        selectProduct(prod, sku)
      }
    })
  })
}
const checkProd = (index) => {
  const prod = dataList.value[index]
  prod.skuList.forEach(sku => {
    // 勾选或取消勾选没有被禁用的sku
    if (!sku.disable) {
      sku.check = prod.check
      selectProduct(prod, sku)
    }
  })
  dataList.value[index] = prod
  checkStatus()
}
const checkSku = (index, skuIndex) => {
  const prod = dataList.value[index]
  let check = true
  for (let i = 0; i < prod.skuList.length; i++) {
    const sku = prod.skuList[i]
    if (check && !sku.check) {
      check = false
    }
    if (skuIndex === i) {
      selectProduct(prod, sku)
    }
  }
  prod.check = check
  dataList.value[index] = prod
  checkStatus()
}
// 商品多规格是否部分选中
const indeterminateItem = () => {
  const prod = dataList.value
  return Boolean(prod.length > 0 && prod.filter((e) => e.check).length > 0 && prod.filter((e) => e.check).length < prod.length)
}
const checkStatus = () => {
  let _checkAll = true
  for (let i = 0; i < dataList.value.length; i++) {
    if (!dataList.value[i].check) {
      _checkAll = false
      break
    }
    const prod = dataList.value[i]
    for (let j = 0; j < prod.skuList.length; j++) {
      if (!prod.skuList[j].check) {
        _checkAll = false
        break
      }
    }
  }
  checkAll.value = _checkAll
}
// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}
/**
 * 清空搜索条件
 */
const clear = () => {
  dataForm.prodName = ''
  dataForm.partyCode = null
}
// 确定事件
const submitProds = () => {
  if (!visible.value) return
  emit('refreshSelectSupplier', selectProds)
  dataListSelections.value = []
  visible.value = false
}
// 取消事件
const back = () => {
  dataListSelections.value = []
  visible.value = false
}

</script>
<style lang="scss" scoped>
.page-supplier-prod-select{
  min-width: 700px;
  .search {
    width: 100%;
  }
  .public-height {
    height: 100%;
  }
  :deep(.clearfix:after) {
    /*伪元素是行内元素 正常浏览器清除浮动方法*/
    content: "";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
  }
  :deep(.clearfix) {
    *zoom: 1; /*ie6清除浮动的方式 *号只有IE6-IE7执行，其他浏览器不执行*/
  }
  .screening-conditions {
    display: block;
    padding: 20px !important;
    background: #f8f8f9;
    margin-bottom: 20px;
  }
  .submit-box {
    display: inline-block;
    margin-top: 15px;
  }
  .mod-order-order {
    .main {
      :deep(.status-nav) {
        position: relative;
        display: block;
        width: 100%;
        margin-bottom: 15px;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #ddd;
        ul,
        li {
          list-style: none;
          padding: 0;
          margin: 0;
        }
        .nav-item {
          float: left;
          height: 40px;
          line-height: 40px;
          background: #F7F8FA;
          border: 1px solid #ddd;
          padding: 0 20px;
          margin: 0 -1px -1px 0;
          cursor: pointer;
        }

        .selected {
          background: #fff;
          border-bottom: 1px solid #fff;
        }
      }
      .tit {
        margin-bottom: 15px;
        background: #F7F8FA;
        z-index: 11;
        height: 57px;
        font-weight: bold;
      }
      .column-title {
        text-align: center;
      }
      .notData-tip{
        text-align: center;
        color:#999;
      }
    }
    .tit {
      display: flex;
      height: 45px;
      align-items: center;
    }
    .tit .item {
      padding: 0 10px;
      width: 10%;
      text-align: center;
    }

    .prod-tit span {
      margin-right: 15px;
    }
    .prod-cont {
      display: flex;
      border: 1px solid #EBEDF0;
      color: #495060;
    }
    .prod-cont .item {
      display: flex;
      display: -webkit-flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      text-align: center;
      height: 100%;
    }

    :deep(.el-button--text) {
      padding-top: 0;
      padding-bottom: 0;
    }
    .item span {
      display: inline-block !important;
    }
    .prod-cont .prod-item {
      display: flex;
      flex-direction: column;
      height: 100%;
    }
    .prod-name {
      width: 55%;
      text-align: left;
      // 超过2行溢出隐藏
      display:-webkit-box;
      word-break: break-word !important;
      -webkit-box-orient:vertical;
      -webkit-line-clamp:2;
      overflow:hidden;
    }

    .prod-price span {
      display: block;
    }
    .prod-price span:first-child {
      margin-bottom: 10px;
    }

    .prod-cont .items.name {
      display: flex;
      align-items: center;
      position: relative;
      padding: 10px;
      border-bottom: 1px solid #EBEDF0;
    }
    .prod-cont .items.name:last-child {
      border-bottom: none;
    }
    .prod-image {
      margin-right: 5px;
      width: 80px;
      height: 80px;
    }
    .prod-image :deep(img) {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    .item span {
      display: block;
    }
  }
  .default-btn + .default-btn {
    margin-left: 0;
  }
  div :deep(.el-tabs__active-bar) {
    width: 0 !important;
  }
  div :deep(.el-tabs__item) {
    padding: 0 20px !important;
    min-width: 68px;
    width: auto;
    text-align: center;
  }
  div :deep(.el-tabs__item.is-active) {
    background: rgba(21, 91, 212, 0.1);
    border-bottom: 2px solid #155BD4;
  }
  .default-btn {
    margin: 0 12px;
  }
}
</style>
